package com.capinfo.accumulation.util;



import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import net.sf.json.JSONException;

/**
 * json 转换工具类
 * @author Administrator
 *
 */
public class JSONUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(JSONUtil.class);

	private static Gson gson = new GsonBuilder().serializeNulls().create();// 保存NULL
	public static String toJsonString(Object o){
		return gson.toJson(o);
	}

	public static String toJsonString(Object o,String  dateFormat){
		Gson gson2 = new GsonBuilder().serializeNulls().setDateFormat(dateFormat).create();
		logger.info(gson2.toJson(o));
		return gson2.toJson(o);
	}
	public static String ToJsongString2(Object o){
		return JSON.toJSONString(o);
	}

	public static Object fromJson(String str,Class beanClass){
		Gson gson = new Gson();
		try {
			if(str!=null){
				Object obj = gson.fromJson(str, beanClass);
				return obj;
			}else{
				logger.info("JSONUtil.fromJson ERR===>>>>>>"+str);
				return null;
			}
		}catch (Exception e){
			logger.info("JSONUtil.fromJson ERR===>>>>>>"+str);
			e.printStackTrace();
		}
		return null;
	}
	
	/**
     * 将Json对象转换成Map
     * 
     * @param jsonObject
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
	
	public static Map toMap(String jsonString) throws JSONException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String ,? >>() {}.getType();  
        Map   map = (Map)gson.fromJson(jsonString, type);
        return map;
    }
	/**
	 * json 转换成List
	 * @param jsonString
	 * @return
	 * @throws JSONException
	 */
	public static List toList(String jsonString) throws JSONException {
        Gson gson = new Gson();
        List list = gson.fromJson(jsonString, new TypeToken<List>(){}.getType());   
        return list;
    }
	
	/**
	 * json转换实体bean
	 * @param json
	 * @param c
	 * @return
	 * @throws Exception
	 */
	public static <T> T converyToJavaBean(String json, Class<T> c)throws Exception {
		Gson gson = new Gson();
		return gson.fromJson(json, c);
	}

}
